package initalize

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"mxshop_srvs/user_srv/global"
	"os"
	"time"
)

func InitDB() {
	//dsn := "root:56248123@tcp(192.168.16.110:3306)/mxshop_user_srv?charset=utf8mb4&parseTime=True&loc=Local"
	c := global.ServerConfig.MysqlInfo
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.User, c.Password, c.Host, c.Port, c.Name,
	)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,  // 慢 SQL 阈值
			LogLevel:      logger.Error, // Log level
			Colorful:      true,         // 禁用彩色打印
		},
	)

	// 全局模式
	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁止表名复数形式, 例如User的表名默认是users
		},
		Logger: newLogger,
	})
	if err != nil {
		zap.S().Panic(err)
	}
	zap.S().Debug("[user-srv] 初始化 Mysql 完成")
	//// 定义一个表结构, 将表结构直接生成对应的表 - migrations
	//// 迁移 schema
	//_ = DB.AutoMigrate(&model.User{})
}
